var t = getApp(),
    e = t.requirejs("core"),
    s = t.requirejs("wxParse/wxParse"),
    c = t.requirejs("check"),
    n = 0,
    r = [],
    d = [];
Page({
    data: {
        route: "goods_detail",
        menu: t.tabBar,
        menu_show: false,
        icons: t.requirejs("icons"),
        goods: {},
        //轮播图
        indicatorDots: true,
        autoplay: true,
        interval: 5000,
        duration: 500,
        circular: true,
        advWidth: 0,  //窗口宽度
        info: "active",//默认展开商品详情
        para: "",//参数
        slider:'',
        buyType: "",
        pickerOption: {},
        specsData: [],
        specsTitle: "",
        tempname: "",//弹框
        showPicker: false,//页面阴暗效果
        total: 1,   //默认选择数量
        canBuy: true,//判断库存
        optionid:0 ,//初始规格未选中的状态。buyNow()调用
        spec_Show:true,
        button_color: t.config.button_color,
        font_color: t.config.font_color,
        config: t.config,
        display:false,
        isOn: false,
        n_animationData: '',
        news_num: 0, //未读消息
        get_phone: false,
        light_star: "/yb_mingpian/static/images/light-star.png",
        is_show_circle: 0,
        product: {}, // 推荐好物信息
        show_rec: 0, // 是否显示海报推荐人
        show_chat: 0, // 是否显示聊天
    },
    loginSubmit: function (k) {
        console.log('登录获取表单id')
        var formid = k.detail.formId;
        getApp().setCache('login_formid', formid);
    },
    onGotUserInfo: function (q) {
        var that = this,
            cache = t.getCache("userinfo");

        // if (cache) {
        //     return;
        // }
        t.getUserInfo(q.detail.userInfo, function (t) {
            if (t != 1000) {
                var ucache = getApp().getCache("userinfo");
                if (ucache) {
                    var options = that.data.options;
                    that.getDetail(options)
                    //getCurrentPages()[getCurrentPages().length - 1].onLoad();
                    that.setData({
                        display: false,
                        getPhoneAuth: getApp().globalData.getphone
                    })
                }
            } else {
                that.setData({
                    display: true
                })
            }

            that.emptyActive();
        }, q.detail.encryptedData, q.detail.iv);
    },

    // 授权获取用户信息判断
    authCheck: function () {
        var cache = getApp().getCache("userinfo");
        if (!cache.nickName && !cache.avatarUrl) {
            this.setData({
                display: true
            })
            return false;
        } else {
            this.setData({
                display: false
            })
            return true;
        }
    },

    // 取消登录
    cancel_auth: function () {
        this.setData({
            display: false
        })
    },

    // 授权时获取用户手机号
    getMobile: function (e) {
        t.globalData.getphone = false;
        this.setData({
            getPhoneAuth: false
        })
        t.getPhoneNumber(e, this, 3);
    },

    // 聊天
    to_chat: function() {
        e.jump('/yb_mingpian/pages/chats/chats');
    },

    // 聊天时获取用户手机号
    getPhoneNumber: function(e) {
        t.getPhoneNumber(e,this,1);
    },

    //底部导航跳转
    menu_url: function (k) {
        e.menu_url(k, 2);
    },

    onLoad: function (ez) {
        var a = this;

        // 好物圈需要微信7.0.3及以上版本支持
        wx.getSystemInfo({ //获取系统资料
            success: function (res) {
                var result = c.compareVersion('7.0.3', res.version);
                if (result <= 0) {
                    a.setData({
                        is_show_circle: 1
                    })
                }

                console.log("result",result)
                a.setData({
                    advWidth: res.windowWidth  //窗口宽度
                })
            }
        })

        var cache = t.getCache("userinfo");
        if (!cache.nickName && !cache.avatarUrl) {
            getApp().authSwitch(function(res){
                if (res == 1) {
                    a.setData({
                        display: true
                    })
                } else {
                    a.setData({
                        display: false
                    })
                }
            })
        }

        console.log("ez",ez)
        console.log("ez1",ez != undefined)
        if (ez != undefined) {
            if (ez.scene) {
                var scene = decodeURIComponent(ez.scene);
                scene = scene.split(',');
                ez.id = scene[0];
                ez.pid = scene[1];
                ez.card_id = scene[2];

                if (ez.card_id != undefined) {
                    t.globalData.card_id = ez.card_id;
                }

                getApp().userlog(6, '商品', 'goods_browse', ez.id);
            } else {
                if (ez.card_id != undefined) {
                    t.globalData.card_id = ez.card_id;
                }
            }
            console.log("123",t.globalData.card_id);
            if (ez && ez.pid) {
                t.set_share_pid(ez.pid);
                t.setCache('pid', ez.pid);
            }
        }

        a.setData({
            options: ez != undefined ? ez : {},//保存商品ID
            //areas: t.getCache("cacheset").areas
            button_color: getApp().config.button_color,
            font_color: getApp().config.font_color,
            config: getApp().config
        }),

        t.get_news_num(a);
    },
    onShow: function () {
        var that=this;
        var options = that.data.options;
        t.set_caidan(function () {
            e.setting();
            that.setData({
                config: getApp().config
            })
        });
        that.getDetail(options)
        that.hideModal();

        //this.history(e)
        that.GoodsClicks(options)
    },

    // 购物车跳转
    url:function(){
        var url="/yb_mingpian/pages/member/cart/index?key=1";
        wx.navigateTo({
            url: url,
            fail: function (i) {
                if (i.errMsg.indexOf("tabbar") >= 0 || i.errMsg.indexOf("tab bar") >= 0) {
                    e.jump(url, 4)
                }
            }
        })
    },

    // 我要咨询
    toConsult: function() {
        var auth_res = this.authCheck();
        if (!auth_res) {
            return;
        }
        e.jump('/yb_mingpian/pages/chats/chats');
    },

    /**
     * 下拉刷新
     */
    onPullDownRefresh: function () {
        wx.stopPullDownRefresh();
    },
    /**
     *访问该页面，对应商品点击量加1
     * @param goods_id
     * @return string
     */
    GoodsClicks: function (t) {
        e.get("goods/GoodsClicks", {
            goods_id: t.id
        }, function (t) {
            //console.log(t)
        })
    },

    /**
     *立即购买
     * @param goods_id sku_id uid total
     * @return url
     */
    buyNow: function (t) {
        var auth_res = this.authCheck();
        if (!auth_res) {
            return;
        }

        //console.log(t)
        var i = this,
            s = i.data.optionid;
        if (i.data.goods.sku.length>1){
            if (s == 0){
                wx.showToast({
                    title: '请选择规格',
                    icon: 'loading',
                    duration: 1000
                })
            }
            wx.redirectTo({
                url: "/yb_mingpian/pages/order/create/index?goods_id=" + i.data.options.id + "&total=" + i.data.total + "&sku_id=" + s + "&uid=" + getApp().getCache("userinfo").uid
            })
        }else{
            wx.redirectTo({
                url: "/yb_mingpian/pages/order/create/index?goods_id=" + i.data.options.id + "&total=" + i.data.total + "&sku_id=" + i.data.goods.sku['0'].sku_id + "&uid=" + getApp().getCache("userinfo").uid
            })
        }

    },

    /**
     * 加入购物车
     * @param goods_id sku_id buyer_id goods_name num goods_images
     * @return string
     */
    getCart: function (t) {
        if (!getApp().getCache("userinfo").uid) {
            var auth_res = this.authCheck();
            if (!auth_res) {
                return;
            }
        }

        var i = this,
            sku_id='',
            s = i.data.optionid;
        if (i.data.goods.sku.length > 1) {
            if (s == 0) {
                e.alert('请选择规格！')
                return;
            }
            sku_id=s
        } else {
            sku_id= i.data.goods.sku['0'].sku_id
        }

        e.get("Cart/AddCart", {
            buyer_id: getApp().getCache("userinfo").uid,
            num: i.data.total,
            sku_id: sku_id,
            goods_id: i.data.goods.goods_id,
            goods_name: i.data.goods.goods_name,
            goods_images: i.data.goods.images
        }, function (t) {
            if(t.code==2){
                var min = i.data.goods.min_buy
                e.alert("最大购买数量"+min)
                return
            }
            0 == t.code ?(
                wx.showToast({
                    title: '成功添加到购物车',
                    icon: 'success',
                    duration: 1500
                }),
                    i.setData({
                        active: "",
                        slider: "out",
                        "goods.cart": parseInt(i.data.goods.cart) + parseInt(i.data.total)
                    })
            ) : e.alert(t.msg)
        })

    },

    /**
     *点击按钮 弹出 选择规格、数量页面
     */
    selectPicker: function (t) {
        var a = this,
            o = t.currentTarget.dataset.tap,
            i = t.currentTarget.dataset.buytype;
        console.log(a.data.total,"aaasa")
        //console.log(o)
        a.setData({
            active: "active",
            slider: "in",
            tempname: "select-picker",
            buyType: i,
            total: a.data.total
        })
        d = this.data.goods.sku
        console.log("guige",this.data.goods)
        console.log("format",a.data.goods.goods_spec_format)
        //默认规格选中
        if (a.data.goods.goods_spec_format.length != 0) {
            var r = a.data.goods.goods_spec_format,
                o = "",
                attr_ids = "",
                arr=[];
            r.forEach(function (t, k) {
                arr[k] = {
                    id: t.spec_id,
                    vid :t.value[0].spec_value_id,
                    spec_name:t.value[0].spec_value_name
                }
                o += t.value[0].spec_value_name + "， "
                attr_ids += t.spec_id + ":" + t.value[0].spec_value_id + ";";
            }),

            a.setData({
                specsData: arr,
                specsTitle: o
            })
            console.log("good_guige",a.data.specsData)
            attr_ids = attr_ids.slice(0, -1);
            console.log("attr_ids",attr_ids)

            // 查询规格库存数据
            e.get("goods/GoodsAttribute", {
                good_id: a.data.goods.goods_id,
                attr_value_items: attr_ids
            }, function (res) {
                console.log("res",res)
                if (res.code == 0) {
                    a.setData({
                        optionid: res.info.sku_id,
                        "goods.stock": res.info.stock,
                        "goods.promote_price": res.info.promote_price,
                        "goods.cost_price": res.info.cost_price,
                        "goods.market_price": res.info.market_price,
                        "goods.price": res.info.price,
                        "goods.sku_pic": res.info.pic != null ? res.info.pic.img_cover : ''
                    })
                    res.info.stock <= 0 ? a.setData({
                        canBuy: false
                    }) : a.setData({
                        canBuy: true
                    })
                } else {
                    a.setData({
                        optionid: d['0'].sku_id,
                        "goods.stock": d['0'].stock,
                        "goods.promote_price": d['0'].promote_price,
                        "goods.cost_price": d['0'].cost_price,
                        "goods.market_price": d['0'].market_price,
                        "goods.price": d['0'].price,
                        "goods.sku_pic": (d['0'].pic!= null) ? d['0'].pic.img_cover:''
                    }),

                    d['0'].stock <= 0 ? a.setData({
                        canBuy: false
                    }) : a.setData({
                        canBuy: true
                    })
                }
            })
        }else{
            d['0'].stock <= 0 ? a.setData({
                canBuy: false
            }) : a.setData({
                canBuy: true
            })
            a.setData({
                "goods.sku_pic": (d['0'].pic != null) ? d['0'].pic.img_cover : ''
            })
        }
    },

    /**
     *选中规格后在data中储存相应的数量、价格、sku等信息
     */
    specsTap: function (t) {
        var e = this,
            o = "",
            i = "",
            a = t.target.dataset.idx;
        r = e.data.specsData;
        r[a] = {
            id: t.target.dataset.id,
            vid: t.target.dataset.vid,
            spec_name: t.target.dataset.spec_name
        };
        r.forEach(function (t) {
            o += t.spec_name + "， ",
                i += t.id+":"+t.vid+";"
        }),
            i = i.substring(0, i.length - 1),
            d.forEach(function (a) {
                //console.log(a)
                a.attr_value_items == i && (e.setData({
                        optionid: a.sku_id,
                        "goods.stock": a.stock,
                        "goods.promote_price": a.promote_price,
                        "goods.cost_price": a.cost_price,
                        "goods.market_price": a.market_price,
                        "goods.price": a.price,
                        "goods.sku_pic": (a.pic!=null) ? a.pic.img_cover : ''
                    }), a.stock <= 0 ? e.setData({
                        canBuy: false
                    }) : e.setData({
                        canBuy:true
                    })
                )
            }),
            e.setData({
                specsData: r,
                specsTitle: o
            })
    },
    /**
     * 改变商品数量
     */
    number: function (t) {
        var o = this,
            s=e.data(t),
            i = e.pdata(t),
            num = parseInt(i.value);
        if (!t.target.dataset.action) {
            return false;
        }
        if ("minus" === s.action) {
            if (num > 1 ) { num = num-1; }
            else { return e.toast("已是最少购买量") }
        } else if ("plus" === s.action) {
            // if (o.data.goods.price == 0) {
            //     e.toast("限购数量为1")
            //     return false;
            // }

            if (num >= i.min && i.min > 0) {
                e.toast("最多购买量为" + i.min)
                return false;
            }

            if (num >= o.data.goods.stock) {
                e.toast("最多购买量为" + o.data.goods.stock)
                return false;
            }

            num = num+1;
        }
        o.setData({
            total: num
        })
    },

    /**
     *隐藏 选选数量、规格的 弹框
     */
    emptyActive: function () {
        this.setData({
            active: "",
            slider: "out",
            //showPicker: false,
        })
    },

    /**
     *获取商品详情信息
     * @param goods_id uid
     * @return array
     */
    getDetail: function (t) {
        var a = this,
            total='';
        getApp().userlog(6, '商品', 'goods_browse', t.id);
        a.setData({
            loading: true
        }),
            console.log('param',t);
        e.get("goods/GoodsDetail", {
            goods_id: t.id,
            uid: getApp().getCache("userinfo").uid != undefined ? getApp().getCache("userinfo").uid : 0
        }, function (t) {
            if (t.code==0)  {
                if (t.info.sku.length == 1) {
                    a.setData({
                        optionid: 0
                    })
                }
                if (t.info.min_buy) {
                    total = 1
                } else {
                    total = 1
                }
                s.wxParse("wxParseData", "html", t.info.description, a, "0"),
                a.setData({
                    show: true,
                    goods: t.info,
                    total: total,
                    show_chat: t.info.show_chat
                })

                wx.setNavigationBarTitle({
                    title: t.info.goods_name || "商品详情"
                })

                // 推荐好物信息
                var product_info = {
                    item_code: t.info.goods_id + '', // 物品ID，开发者自定义的ID，需要保证唯一性
                    title: t.info.goods_name, // 物品名称
                    image_list: [t.info.pic[0]['img_cover']] // 物品高清图URL列表，要求图片宽度大于750px，宽高比在4:3 - 1:1之间
                };
                a.setData({
                    product: product_info
                })
            }else{
                e.alert(t.msg)
            }
        })
    },

    /**
     * 推荐商品到好物圈，调用openBusinessView接口前，判断当前用户的微信是否支持（微信7.0.3及以上版本支持）
     */
    addGoodThingCircle: function () {
        wx.openBusinessView({
            businessType: 'friendGoodsRecommend',
            extraData: {
                product: this.data.product
            },
            success: function (res) {
                console.log("推荐好物成功",res);
            },
            fail: function (res) {
                console.log("推荐好物失败",res);
            }
        })
    },

    /**
     *商品详情模块、商品属性模块切换
     * @param para  商品属性
     * @param info 商品详情
     * @return string
     */
    goodsTab: function (t) {
        var a = this,
            o = t.currentTarget.dataset.tap;
        if ("info" == o)
            this.setData({
                info: "active",
                para: "",
              comment: ""
            });
        else if ("para" == o)
            this.setData({
                info: "",
                para: "active",
              comment: ""
            });
        else if ("comment" == o)
            this.setData({
              info: "",
              para: "",
              comment: "active"
            });
    },

    /**
     *商品收藏
     * @param fav_id  商品id
     * @param log_price 收藏时的价格
     * @param uid 用户id
     * @return string
     */
    favorite: function (t) {
        var a = this,
            o = t.currentTarget.dataset.logprice;
        e.get("goods/Favorites", {
            fav_id: a.data.options.id,
            log_price: o,
            uid:getApp().getCache("userinfo").uid
        }, function (t) {
            0 == t.code ? (
                t.info.status == 1 ? a.setData({ //异步刷新页面
                    "goods.favorites": true
                }) : a.setData({
                    "goods.favorites": false
                })
            ): e.alert(t.msg)


        })
    },

    // 底部弹窗设置
    show_Modal: function () {
        var that = this;

        e.get("poster/getConf", {
            type: 1
        }, function (res) {
            if (res.code == 0) {
                that.setData({
                    show_rec: res.info.is_set
                })
            }

            var cache = getApp().getCache('userinfo');
            if (!cache.nickName && !cache.avatarUrl) {
                that.setData({
                    show_rec: false
                })
            }

            // 显示遮罩层
            var animation = wx.createAnimation({ //创建一个动画实例 animation。调用实例的方法来描述动画。最后通过动画实例的 export 方法导出动画数据传递给组件的 animation 属性。
                duration: 200,
                timingFunction: "ease-in-out",
                delay: 0
            })

            that.animation = animation
            animation.translateY(500).step() //对 Y 轴平移 单位为 px
            //.step() 表示一组动画完成。可以在一组动画中调用任意多个动画方法，一组动画中的所有动画会同时开始，一组动画完成后才会进行下一组动画。
            that.setData({
                animationData: animation.export(), //导出动画队列。export 方法每次调用后会清掉之前的动画操作。
                isOn: true
            })
            setTimeout(function () {
                animation.translateY(0).step()
                that.setData({
                    animationData: animation.export()
                })
            }.bind(that), 200)
        })
    },

    hideModal: function () {
        this.setData({
            isOn: false,
        })
    },

    //分享
    onShareAppMessage: function () {
        this.hideModal();
        var title = this.data.goods.goods_name,
            cache = getApp().getCache('userinfo');
        var uid = cache.uid ? cache.uid : 0;

        if (!cache.nickName && !cache.avatarUrl) {
            uid = 0;
        }

        t.userlog(2, '商品', 'goods_relay');

        var path = '/yb_mingpian/pages/goods/detail/index?id=' + this.data.goods.goods_id + '&pid=' + uid + "&card_id=" + t.globalData.card_id;
        console.log("a0", path);
        return {
            title: title,
            path: path
        }
    },
})